package com.by.token;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.by.auto.TokenProperties;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 江俊俊
 * @version 1.0
 * @description
 * @date 2025/2/12 19:01
 * @since JDK1.8
 */
public class TokenTemplate {



    TokenProperties tokenProperties;
    public TokenTemplate(TokenProperties tokenProperties) {
        this.tokenProperties = tokenProperties;
    }
    /**
     * 生成token
     *
     * @param payload
     * @return
     */
    public String generateToken(Map payload) {
        String token=JWT.create()
                .withHeader(getHeader())
                .withPayload(payload)
                .withIssuer("by")
                .withExpiresAt(getExpireDate())
                .sign(Algorithm.HMAC256(tokenProperties.getSecret()));
        return token;
    }

    public Result valid(String token) {
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(tokenProperties.getSecret()))
                .build();
        DecodedJWT decodedJWT = null;
        try {
            decodedJWT = verifier.verify(token);
        } catch (JWTDecodeException e) {
            return new Result(1, "token无效", null);
        } catch (TokenExpiredException e) {
            return new Result(2, "token过期", null);
        }
        Map<String, Claim> payload = decodedJWT.getClaims();
        Map<String, Object> temp = new HashMap<>();
        temp.put("id", payload.get("id").asInt());
        temp.put("username", payload.get("username").asString());
        return new Result(3, "token有效", temp);
    }

    /**
     * 获取过期时间
     *
     * @return
     */
    Date getExpireDate() {
        return new Date(System.currentTimeMillis());
    }

    /**
     * 获取头部
     *
     * @return
     */
    Map getHeader() {
        Map<String, String> map = new HashMap();
        map.put("type", "JWT");
        map.put("alg", "HMAC256");
        return map;
    }
}
